using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;

namespace Chat.Backend.Services.Call
{
    /// <summary>
    /// 音视频通话服务 - 处理语音和视频通话的信令和状态管理
    /// 转换自Java代码的call模块
    /// </summary>
    public class CallService : ICallService
    {
        private readonly ILogger<CallService> _logger;
        private readonly IXmppService _xmppService;
        private readonly IUserService _userService;
        private readonly IEventBus _eventBus;
        private readonly IPushService _pushService;
        
        // 存储当前活跃的通话会话
        private readonly ConcurrentDictionary<string, CallSession> _activeCalls = new ConcurrentDictionary<string, CallSession>();
        
        // 存储超时取消的计时器
        private readonly ConcurrentDictionary<string, CancellationTokenSource> _callTimeoutTokens = new ConcurrentDictionary<string, CancellationTokenSource>();

        /// <summary>
        /// 构造函数
        /// </summary>
        public CallService(
            ILogger<CallService> logger,
            IXmppService xmppService,
            IUserService userService,
            IEventBus eventBus,
            IPushService pushService)
        {
            _logger = logger;
            _xmppService = xmppService;
            _userService = userService;
            _eventBus = eventBus;
            _pushService = pushService;
            
            // 订阅XMPP消息接收事件，用于处理通话信令
            _eventBus.Subscribe<XmppMessageReceivedEvent>(OnMessageReceived);
        }

        /// <summary>
        /// 发起通话请求
        /// </summary>
        public async Task<CallResult> InitiateCallAsync(string callerId, string calleeId, bool isVideoCall)
        {
            try
            {
                // 检查发起者和接收者是否存在
                var caller = await _userService.GetUserByIdAsync(callerId);
                var callee = await _userService.GetUserByIdAsync(calleeId);
                
                if (caller == null || callee == null)
                {
                    throw new ArgumentException("发起者或接收者不存在");
                }
                
                // 检查接收者是否在线
                var isCalleeOnline = await _userService.IsUserOnlineAsync(calleeId);
                
                // 创建通话会话
                var callId = Guid.NewGuid().ToString();
                var callType = isVideoCall ? CallType.Video : CallType.Audio;
                
                var callSession = new CallSession
                {
                    CallId = callId,
                    CallerId = callerId,
                    CalleeId = calleeId,
                    CallType = callType,
                    StartTime = DateTime.UtcNow,
                    Status = CallStatus.Ringing
                };
                
                // 保存通话会话
                _activeCalls[callId] = callSession;
                
                // 构建通话信令消息
                var signalingMessage = new CallSignalingMessage
                {
                    Type = "call_offer",
                    CallId = callId,
                    CallerId = callerId,
                    CallerName = caller.Nickname,
                    CallType = callType.ToString().ToLowerInvariant(),
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
                    SdpOffer = null, // SDP在前端生成后通过另一条消息发送
                    IceServers = GetIceServers() // TURN/STUN服务器配置
                };
                
                var messageJson = System.Text.Json.JsonSerializer.Serialize(signalingMessage);
                
                // 发送XMPP消息
                var xmppTo = $"{calleeId}@{_xmppService.Domain}";
                await _xmppService.SendMessageAsync(xmppTo, messageJson, MessageType.Chat);
                
                // 如果接收者不在线，发送推送通知
                if (!isCalleeOnline)
                {
                    await _pushService.SendCallPushNotificationAsync(
                        calleeId,
                        $"{caller.Nickname}正在呼叫你",
                        isVideoCall ? "视频通话" : "语音通话",
                        new Dictionary<string, string>
                        {
                            { "callId", callId },
                            { "callerId", callerId },
                            { "callType", callType.ToString() }
                        }
                    );
                }
                
                // 设置通话超时计时器（30秒）
                var tokenSource = new CancellationTokenSource();
                _callTimeoutTokens[callId] = tokenSource;
                
                _ = Task.Delay(TimeSpan.FromSeconds(30), tokenSource.Token)
                    .ContinueWith(async task =>
                    {
                        if (!task.IsCanceled)
                        {
                            await HandleCallTimeoutAsync(callId);
                        }
                    }, TaskScheduler.Default);
                
                return new CallResult
                {
                    Success = true,
                    CallId = callId
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"发起通话失败: 从 {callerId} 到 {calleeId}");
                return new CallResult
                {
                    Success = false,
                    Error = ex.Message
                };
            }
        }

        /// <summary>
        /// 接受通话请求
        /// </summary>
        public async Task<CallResult> AcceptCallAsync(string callId, string userId)
        {
            try
            {
                // 检查通话是否存在
                if (!_activeCalls.TryGetValue(callId, out var callSession))
                {
                    throw new ArgumentException("通话不存在或已结束");
                }
                
                // 检查用户是否是被叫方
                if (callSession.CalleeId != userId)
                {
                    throw new ArgumentException("只有被叫方可以接受通话");
                }
                
                // 检查通话状态
                if (callSession.Status != CallStatus.Ringing)
                {
                    throw new ArgumentException("通话已被应答或已结束");
                }
                
                // 更新通话状态
                callSession.Status = CallStatus.Accepted;
                callSession.AcceptTime = DateTime.UtcNow;
                
                // 取消超时计时器
                if (_callTimeoutTokens.TryRemove(callId, out var tokenSource))
                {
                    tokenSource.Cancel();
                    tokenSource.Dispose();
                }
                
                // 构建接受通话信令消息
                var signalingMessage = new CallSignalingMessage
                {
                    Type = "call_accept",
                    CallId = callId,
                    CalleeId = userId,
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                };
                
                var messageJson = System.Text.Json.JsonSerializer.Serialize(signalingMessage);
                
                // 发送XMPP消息
                var xmppTo = $"{callSession.CallerId}@{_xmppService.Domain}";
                await _xmppService.SendMessageAsync(xmppTo, messageJson, MessageType.Chat);
                
                return new CallResult
                {
                    Success = true,
                    CallId = callId
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"接受通话失败: 通话ID {callId}, 用户ID {userId}");
                return new CallResult
                {
                    Success = false,
                    Error = ex.Message
                };
            }
        }

        /// <summary>
        /// 拒绝通话请求
        /// </summary>
        public async Task<CallResult> RejectCallAsync(string callId, string userId)
        {
            try
            {
                // 检查通话是否存在
                if (!_activeCalls.TryGetValue(callId, out var callSession))
                {
                    throw new ArgumentException("通话不存在或已结束");
                }
                
                // 检查用户是否是被叫方
                if (callSession.CalleeId != userId)
                {
                    throw new ArgumentException("只有被叫方可以拒绝通话");
                }
                
                // 检查通话状态
                if (callSession.Status != CallStatus.Ringing)
                {
                    throw new ArgumentException("通话已被应答或已结束");
                }
                
                // 更新通话状态
                callSession.Status = CallStatus.Rejected;
                callSession.EndTime = DateTime.UtcNow;
                
                // 取消超时计时器
                if (_callTimeoutTokens.TryRemove(callId, out var tokenSource))
                {
                    tokenSource.Cancel();
                    tokenSource.Dispose();
                }
                
                // 构建拒绝通话信令消息
                var signalingMessage = new CallSignalingMessage
                {
                    Type = "call_reject",
                    CallId = callId,
                    CalleeId = userId,
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                };
                
                var messageJson = System.Text.Json.JsonSerializer.Serialize(signalingMessage);
                
                // 发送XMPP消息
                var xmppTo = $"{callSession.CallerId}@{_xmppService.Domain}";
                await _xmppService.SendMessageAsync(xmppTo, messageJson, MessageType.Chat);
                
                // 从活跃通话列表中移除
                _activeCalls.TryRemove(callId, out _);
                
                return new CallResult
                {
                    Success = true,
                    CallId = callId
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"拒绝通话失败: 通话ID {callId}, 用户ID {userId}");
                return new CallResult
                {
                    Success = false,
                    Error = ex.Message
                };
            }
        }

        /// <summary>
        /// 结束通话
        /// </summary>
        public async Task<CallResult> HangupCallAsync(string callId, string userId)
        {
            try
            {
                // 检查通话是否存在
                if (!_activeCalls.TryGetValue(callId, out var callSession))
                {
                    throw new ArgumentException("通话不存在或已结束");
                }
                
                // 检查用户是否是通话参与者
                if (callSession.CallerId != userId && callSession.CalleeId != userId)
                {
                    throw new ArgumentException("只有通话参与者可以结束通话");
                }
                
                // 更新通话状态
                callSession.Status = CallStatus.Ended;
                callSession.EndTime = DateTime.UtcNow;
                
                // 取消超时计时器
                if (_callTimeoutTokens.TryRemove(callId, out var tokenSource))
                {
                    tokenSource.Cancel();
                    tokenSource.Dispose();
                }
                
                // 构建结束通话信令消息
                var signalingMessage = new CallSignalingMessage
                {
                    Type = "call_hangup",
                    CallId = callId,
                    UserId = userId,
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                };
                
                var messageJson = System.Text.Json.JsonSerializer.Serialize(signalingMessage);
                
                // 发送XMPP消息
                var recipientId = userId == callSession.CallerId ? callSession.CalleeId : callSession.CallerId;
                var xmppTo = $"{recipientId}@{_xmppService.Domain}";
                await _xmppService.SendMessageAsync(xmppTo, messageJson, MessageType.Chat);
                
                // 从活跃通话列表中移除
                _activeCalls.TryRemove(callId, out _);
                
                // 记录通话记录
                await RecordCallHistoryAsync(callSession);
                
                return new CallResult
                {
                    Success = true,
                    CallId = callId
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"结束通话失败: 通话ID {callId}, 用户ID {userId}");
                return new CallResult
                {
                    Success = false,
                    Error = ex.Message
                };
            }
        }

        /// <summary>
        /// 发送SDP提议
        /// </summary>
        public async Task<CallResult> SendSdpOfferAsync(string callId, string userId, string sdpOffer)
        {
            try
            {
                // 检查通话是否存在
                if (!_activeCalls.TryGetValue(callId, out var callSession))
                {
                    throw new ArgumentException("通话不存在或已结束");
                }
                
                // 检查用户是否是主叫方
                if (callSession.CallerId != userId)
                {
                    throw new ArgumentException("只有主叫方可以发送SDP提议");
                }
                
                // 构建SDP提议信令消息
                var signalingMessage = new CallSignalingMessage
                {
                    Type = "sdp_offer",
                    CallId = callId,
                    UserId = userId,
                    SdpOffer = sdpOffer,
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                };
                
                var messageJson = System.Text.Json.JsonSerializer.Serialize(signalingMessage);
                
                // 发送XMPP消息
                var xmppTo = $"{callSession.CalleeId}@{_xmppService.Domain}";
                await _xmppService.SendMessageAsync(xmppTo, messageJson, MessageType.Chat);
                
                return new CallResult
                {
                    Success = true,
                    CallId = callId
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"发送SDP提议失败: 通话ID {callId}, 用户ID {userId}");
                return new CallResult
                {
                    Success = false,
                    Error = ex.Message
                };
            }
        }

        /// <summary>
        /// 发送SDP应答
        /// </summary>
        public async Task<CallResult> SendSdpAnswerAsync(string callId, string userId, string sdpAnswer)
        {
            try
            {
                // 检查通话是否存在
                if (!_activeCalls.TryGetValue(callId, out var callSession))
                {
                    throw new ArgumentException("通话不存在或已结束");
                }
                
                // 检查用户是否是被叫方
                if (callSession.CalleeId != userId)
                {
                    throw new ArgumentException("只有被叫方可以发送SDP应答");
                }
                
                // 构建SDP应答信令消息
                var signalingMessage = new CallSignalingMessage
                {
                    Type = "sdp_answer",
                    CallId = callId,
                    UserId = userId,
                    SdpAnswer = sdpAnswer,
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                };
                
                var messageJson = System.Text.Json.JsonSerializer.Serialize(signalingMessage);
                
                // 发送XMPP消息
                var xmppTo = $"{callSession.CallerId}@{_xmppService.Domain}";
                await _xmppService.SendMessageAsync(xmppTo, messageJson, MessageType.Chat);
                
                return new CallResult
                {
                    Success = true,
                    CallId = callId
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"发送SDP应答失败: 通话ID {callId}, 用户ID {userId}");
                return new CallResult
                {
                    Success = false,
                    Error = ex.Message
                };
            }
        }

        /// <summary>
        /// 发送ICE候选
        /// </summary>
        public async Task<CallResult> SendIceCandidateAsync(string callId, string userId, string iceCandidate)
        {
            try
            {
                // 检查通话是否存在
                if (!_activeCalls.TryGetValue(callId, out var callSession))
                {
                    throw new ArgumentException("通话不存在或已结束");
                }
                
                // 检查用户是否是通话参与者
                if (callSession.CallerId != userId && callSession.CalleeId != userId)
                {
                    throw new ArgumentException("只有通话参与者可以发送ICE候选");
                }
                
                // 确定接收者
                var recipientId = userId == callSession.CallerId ? callSession.CalleeId : callSession.CallerId;
                
                // 构建ICE候选信令消息
                var signalingMessage = new CallSignalingMessage
                {
                    Type = "ice_candidate",
                    CallId = callId,
                    UserId = userId,
                    IceCandidate = iceCandidate,
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                };
                
                var messageJson = System.Text.Json.JsonSerializer.Serialize(signalingMessage);
                
                // 发送XMPP消息
                var xmppTo = $"{recipientId}@{_xmppService.Domain}";
                await _xmppService.SendMessageAsync(xmppTo, messageJson, MessageType.Chat);
                
                return new CallResult
                {
                    Success = true,
                    CallId = callId
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"发送ICE候选失败: 通话ID {callId}, 用户ID {userId}");
                return new CallResult
                {
                    Success = false,
                    Error = ex.Message
                };
            }
        }

        /// <summary>
        /// 处理通话超时
        /// </summary>
        private async Task HandleCallTimeoutAsync(string callId)
        {
            try
            {
                // 检查通话是否存在
                if (!_activeCalls.TryGetValue(callId, out var callSession))
                {
                    return;
                }
                
                // 检查通话状态
                if (callSession.Status != CallStatus.Ringing)
                {
                    return;
                }
                
                // 更新通话状态
                callSession.Status = CallStatus.Missed;
                callSession.EndTime = DateTime.UtcNow;
                
                // 构建超时信令消息
                var signalingMessage = new CallSignalingMessage
                {
                    Type = "call_timeout",
                    CallId = callId,
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                };
                
                var messageJson = System.Text.Json.JsonSerializer.Serialize(signalingMessage);
                
                // 发送XMPP消息给主叫方
                var xmppTo = $"{callSession.CallerId}@{_xmppService.Domain}";
                await _xmppService.SendMessageAsync(xmppTo, messageJson, MessageType.Chat);
                
                // 从活跃通话列表中移除
                _activeCalls.TryRemove(callId, out _);
                
                // 记录通话记录
                await RecordCallHistoryAsync(callSession);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"处理通话超时失败: 通话ID {callId}");
            }
        }

        /// <summary>
        /// 处理接收到的XMPP消息
        /// </summary>
        private async Task OnMessageReceived(XmppMessageReceivedEvent evt)
        {
            try
            {
                // 尝试解析为通话信令消息
                var signalingMessage = System.Text.Json.JsonSerializer.Deserialize<CallSignalingMessage>(evt.Body);
                
                if (signalingMessage == null || string.IsNullOrEmpty(signalingMessage.Type))
                {
                    return; // 不是通话信令消息
                }
                
                // 根据消息类型处理
                switch (signalingMessage.Type)
                {
                    case "call_offer":
                        await HandleCallOfferAsync(signalingMessage, evt.From);
                        break;
                        
                    case "call_accept":
                        await HandleCallAcceptAsync(signalingMessage);
                        break;
                        
                    case "call_reject":
                        await HandleCallRejectAsync(signalingMessage);
                        break;
                        
                    case "call_hangup":
                        await HandleCallHangupAsync(signalingMessage);
                        break;
                        
                    case "sdp_offer":
                        await HandleSdpOfferAsync(signalingMessage);
                        break;
                        
                    case "sdp_answer":
                        await HandleSdpAnswerAsync(signalingMessage);
                        break;
                        
                    case "ice_candidate":
                        await HandleIceCandidateAsync(signalingMessage);
                        break;
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理通话信令消息失败");
            }
        }

        /// <summary>
        /// 获取TURN/STUN服务器配置
        /// </summary>
        private List<IceServer> GetIceServers()
        {
            return new List<IceServer>
            {
                new IceServer
                {
                    Urls = new List<string> { "stun:stun.l.google.com:19302" }
                },
                new IceServer
                {
                    Urls = new List<string> { "turn:your-turn-server.com:3478" },
                    Username = "username",
                    Credential = "password"
                }
            };
        }

        /// <summary>
        /// 记录通话历史
        /// </summary>
        private async Task RecordCallHistoryAsync(CallSession callSession)
        {
            try
            {
                var callHistory = new CallHistory
                {
                    CallId = callSession.CallId,
                    CallerId = callSession.CallerId,
                    CalleeId = callSession.CalleeId,
                    CallType = callSession.CallType,
                    Status = callSession.Status,
                    StartTime = callSession.StartTime,
                    AcceptTime = callSession.AcceptTime,
                    EndTime = callSession.EndTime ?? DateTime.UtcNow,
                                        Duration = callSession.AcceptTime.HasValue && callSession.EndTime.HasValue
                        ? (int)(callSession.EndTime.Value - callSession.AcceptTime.Value).TotalSeconds
                        : 0
                };
                
                await _callRepository.SaveCallHistoryAsync(callHistory);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"记录通话历史失败: 通话ID {callSession.CallId}");
            }
        }

        /// <summary>
        /// 处理通话请求消息
        /// </summary>
        private async Task HandleCallOfferAsync(CallSignalingMessage message, string fromJid)
        {
            try
            {
                var callerId = message.CallerId;
                var callId = message.CallId;
                
                // 解析callType
                Enum.TryParse<CallType>(message.CallType, true, out var callType);
                
                // 解析被叫方ID
                var calleeJid = fromJid.Split('@')[0];
                
                // 创建通话会话
                var callSession = new CallSession
                {
                    CallId = callId,
                    CallerId = callerId,
                    CalleeId = calleeJid,
                    CallType = callType,
                    StartTime = DateTime.UtcNow,
                    Status = CallStatus.Ringing
                };
                
                // 保存通话会话
                _activeCalls[callId] = callSession;
                
                // 设置通话超时计时器（30秒）
                var tokenSource = new CancellationTokenSource();
                _callTimeoutTokens[callId] = tokenSource;
                
                _ = Task.Delay(TimeSpan.FromSeconds(30), tokenSource.Token)
                    .ContinueWith(async task =>
                    {
                        if (!task.IsCanceled)
                        {
                            await HandleCallTimeoutAsync(callId);
                        }
                    }, TaskScheduler.Default);
                
                // 通知应用层有新的通话请求
                await _eventBus.PublishAsync(new CallOfferReceivedEvent
                {
                    CallId = callId,
                    CallerId = callerId,
                    CallerName = message.CallerName,
                    CallType = callType,
                    IceServers = message.IceServers
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"处理通话请求失败: {message.CallId}");
            }
        }

        /// <summary>
        /// 处理接受通话消息
        /// </summary>
        private async Task HandleCallAcceptAsync(CallSignalingMessage message)
        {
            try
            {
                var callId = message.CallId;
                
                // 检查通话是否存在
                if (!_activeCalls.TryGetValue(callId, out var callSession))
                {
                    _logger.LogWarning($"通话不存在或已结束: {callId}");
                    return;
                }
                
                // 更新通话状态
                callSession.Status = CallStatus.Accepted;
                callSession.AcceptTime = DateTime.UtcNow;
                
                // 取消超时计时器
                if (_callTimeoutTokens.TryRemove(callId, out var tokenSource))
                {
                    tokenSource.Cancel();
                    tokenSource.Dispose();
                }
                
                // 通知应用层通话已被接受
                await _eventBus.PublishAsync(new CallAcceptedEvent
                {
                    CallId = callId,
                    CalleeId = message.CalleeId
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"处理接受通话消息失败: {message.CallId}");
            }
        }

        /// <summary>
        /// 处理拒绝通话消息
        /// </summary>
        private async Task HandleCallRejectAsync(CallSignalingMessage message)
        {
            try
            {
                var callId = message.CallId;
                
                // 检查通话是否存在
                if (!_activeCalls.TryGetValue(callId, out var callSession))
                {
                    _logger.LogWarning($"通话不存在或已结束: {callId}");
                    return;
                }
                
                // 更新通话状态
                callSession.Status = CallStatus.Rejected;
                callSession.EndTime = DateTime.UtcNow;
                
                // 取消超时计时器
                if (_callTimeoutTokens.TryRemove(callId, out var tokenSource))
                {
                    tokenSource.Cancel();
                    tokenSource.Dispose();
                }
                
                // 从活跃通话列表中移除
                _activeCalls.TryRemove(callId, out _);
                
                // 记录通话历史
                await RecordCallHistoryAsync(callSession);
                
                // 通知应用层通话已被拒绝
                await _eventBus.PublishAsync(new CallRejectedEvent
                {
                    CallId = callId,
                    CalleeId = message.CalleeId
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"处理拒绝通话消息失败: {message.CallId}");
            }
        }

        /// <summary>
        /// 处理结束通话消息
        /// </summary>
        private async Task HandleCallHangupAsync(CallSignalingMessage message)
        {
            try
            {
                var callId = message.CallId;
                
                // 检查通话是否存在
                if (!_activeCalls.TryGetValue(callId, out var callSession))
                {
                    _logger.LogWarning($"通话不存在或已结束: {callId}");
                    return;
                }
                
                // 更新通话状态
                callSession.Status = CallStatus.Ended;
                callSession.EndTime = DateTime.UtcNow;
                
                // 取消超时计时器
                if (_callTimeoutTokens.TryRemove(callId, out var tokenSource))
                {
                    tokenSource.Cancel();
                    tokenSource.Dispose();
                }
                
                // 从活跃通话列表中移除
                _activeCalls.TryRemove(callId, out _);
                
                // 记录通话历史
                await RecordCallHistoryAsync(callSession);
                
                // 通知应用层通话已结束
                await _eventBus.PublishAsync(new CallHangupEvent
                {
                    CallId = callId,
                    UserId = message.UserId
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"处理结束通话消息失败: {message.CallId}");
            }
        }

        /// <summary>
        /// 处理SDP提议消息
        /// </summary>
        private async Task HandleSdpOfferAsync(CallSignalingMessage message)
        {
            try
            {
                // 通知应用层收到SDP提议
                await _eventBus.PublishAsync(new SdpOfferReceivedEvent
                {
                    CallId = message.CallId,
                    UserId = message.UserId,
                    SdpOffer = message.SdpOffer
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"处理SDP提议消息失败: {message.CallId}");
            }
        }

        /// <summary>
        /// 处理SDP应答消息
        /// </summary>
        private async Task HandleSdpAnswerAsync(CallSignalingMessage message)
        {
            try
            {
                // 通知应用层收到SDP应答
                await _eventBus.PublishAsync(new SdpAnswerReceivedEvent
                {
                    CallId = message.CallId,
                    UserId = message.UserId,
                    SdpAnswer = message.SdpAnswer
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"处理SDP应答消息失败: {message.CallId}");
            }
        }

        /// <summary>
        /// 处理ICE候选消息
        /// </summary>
        private async Task HandleIceCandidateAsync(CallSignalingMessage message)
        {
            try
            {
                // 通知应用层收到ICE候选
                await _eventBus.PublishAsync(new IceCandidateReceivedEvent
                {
                    CallId = message.CallId,
                    UserId = message.UserId,
                    IceCandidate = message.IceCandidate
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"处理ICE候选消息失败: {message.CallId}");
            }
        }
    }

    /// <summary>
    /// 通话服务接口
    /// </summary>
    public interface ICallService
    {
        Task<CallResult> InitiateCallAsync(string callerId, string calleeId, bool isVideoCall);
        Task<CallResult> AcceptCallAsync(string callId, string userId);
        Task<CallResult> RejectCallAsync(string callId, string userId);
        Task<CallResult> HangupCallAsync(string callId, string userId);
        Task<CallResult> SendSdpOfferAsync(string callId, string userId, string sdpOffer);
        Task<CallResult> SendSdpAnswerAsync(string callId, string userId, string sdpAnswer);
        Task<CallResult> SendIceCandidateAsync(string callId, string userId, string iceCandidate);
    }
}